<template>
  <ContentWrap>
    <!-- 搜索工作栏 -->
    <el-form
      class="-mb-15px"
      :model="queryParams"
      ref="queryFormRef"
      :inline="true"
      label-width="68px"
    >
      <el-form-item label="配餐单位" prop="mealUnit">
        <el-input
          v-model="queryParams.mealUnit"
          placeholder="请输入配餐单位"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item label="航班号" prop="flightNo">
        <el-input
          v-model="queryParams.flightNo"
          placeholder="请输入航班号"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item label="机型" prop="aircraftType">
        <el-input
          v-model="queryParams.aircraftType"
          placeholder="请输入机型"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item label="起飞站点" prop="depIata">
        <el-input
          v-model="queryParams.depIata"
          placeholder="请输入起飞地点"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item label="降落地点" prop="arrLoc">
        <el-input
          v-model="queryParams.arrLoc"
          placeholder="请输入降落地点"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item label="机组餐谱" prop="crewMeal">
        <el-input
          v-model="queryParams.crewMeal"
          placeholder="请输入机组餐谱"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item>
        <el-button @click="handleQuery"><Icon icon="ep:search" class="mr-5px" /> 搜索</el-button>
        <el-button @click="resetQuery"><Icon icon="ep:refresh" class="mr-5px" /> 重置</el-button>
        <el-button
          type="warning"
          plain
          @click="handleImport"
          v-hasPermi="['distm:quarter-plan:import']"
        >
          <Icon icon="ep:upload" /> 导入
        </el-button>
        <el-button
          type="success"
          plain
          @click="handleExport"
          :loading="exportLoading"
          v-hasPermi="['distm:quarter-plan:export']"
        >
          <Icon icon="ep:download" class="mr-5px" /> 导出
        </el-button>
      </el-form-item>
    </el-form>
  </ContentWrap>

  <!-- 列表 -->
  <ContentWrap>
    <el-table v-loading="loading" :data="list" :stripe="true" :show-overflow-tooltip="true">
      <!-- 序号列 - 移除v-if控制，使其始终显示 -->
      <el-table-column label="序号" type="index" align="center" width="80">
        <template #header>
          <div
            @click="openColumnSetting"
            style="
              display: flex;
              align-items: center;
              justify-content: center;
              cursor: pointer;
              color: #43a2ff;
            "
          >
            <Icon icon="ep:setting" class="mr-5px" /> 序号
          </div>
        </template>
      </el-table-column>

      <el-table-column
        v-if="columnVisibility.mealUnit"
        label="配餐单位"
        align="center"
        prop="mealUnit"
        width="180"
      />

      <el-table-column
        v-if="columnVisibility.flightNo"
        label="航班号"
        align="center"
        prop="flightNo"
      />

      <el-table-column
        v-if="columnVisibility.aircraftType"
        label="机型"
        align="center"
        prop="aircraftType"
      />

      <el-table-column
        v-if="columnVisibility.schPat"
        label="班期"
        align="center"
        prop="schPat"
        width="100"
      />

      <el-table-column
        v-if="columnVisibility.depLoc"
        label="起飞地点"
        align="center"
        prop="depLoc"
      />

      <el-table-column
        v-if="columnVisibility.depIata"
        label="三字代码"
        align="center"
        prop="depIata"
      />

      <el-table-column
        v-if="columnVisibility.depTime"
        label="起飞时间"
        align="center"
        prop="depTime"
      />

      <el-table-column
        v-if="columnVisibility.arrLoc"
        label="降落地点"
        align="center"
        prop="arrLoc"
        width="100"
      />

      <el-table-column
        v-if="columnVisibility.arrIata"
        label="三字代码"
        align="center"
        prop="arrIata"
      />

      <el-table-column
        v-if="columnVisibility.arrTime"
        label="降落时间"
        align="center"
        prop="arrTime"
      />

      <el-table-column
        v-if="columnVisibility.flyDur"
        label="公布飞行时长"
        align="center"
        prop="flyDur"
      />

      <el-table-column
        v-if="columnVisibility.avgActualDur"
        label="平均飞行时长"
        align="center"
        prop="avgActualDur"
      />

      <el-table-column
        v-if="columnVisibility.flightType"
        label="航班性质"
        align="center"
        prop="flightType"
      />

      <el-table-column
        v-if="columnVisibility.bussClassMealQty"
        label="商务舱"
        align="center"
        prop="bussClassMealQty"
        width="180"
      />

      <el-table-column
        v-if="columnVisibility.premEcoClassMeal"
        label="高级经济舱"
        align="center"
        prop="premEcoClassMeal"
        width="180"
      />

      <el-table-column
        v-if="columnVisibility.ecoClassMeal"
        label="经济舱"
        align="center"
        prop="ecoClassMeal"
        width="180"
      />

      <el-table-column
        v-if="columnVisibility.crewMeal"
        label="机组"
        align="center"
        prop="crewMeal"
        width="180"
      />

      <el-table-column
        v-if="columnVisibility.weeklyMealQty"
        label="周配餐量"
        align="center"
        prop="weeklyMealQty"
      />

      <el-table-column
        v-if="columnVisibility.airlineComp"
        label="所属公司"
        align="center"
        prop="airlineComp"
      />

      <el-table-column
        v-if="columnVisibility.airlineIata"
        label="所属公司三字代码"
        align="center"
        prop="airlineIata"
      />

      <el-table-column
        v-if="columnVisibility.airlineType"
        label="航线类别"
        align="center"
        prop="airlineType"
        width="180"
      />

      <el-table-column
        v-if="columnVisibility.effectiveDate"
        label="执行日期"
        align="center"
        prop="effectiveDate"
        width="180"
      />

      <el-table-column v-if="columnVisibility.remarks" label="备注" align="center" prop="remarks" />

      <el-table-column
        v-if="columnVisibility.isWaterPkg"
        label="小水放袋/盒"
        align="center"
        prop="isWaterPkg"
      />

      <el-table-column
        v-if="columnVisibility.isConnFlight"
        label="联程航班"
        align="center"
        prop="isConnFlight"
      />

      <el-table-column
        v-if="columnVisibility.cateringSite"
        label="航食站点"
        align="center"
        prop="cateringSite"
      />

      <el-table-column v-if="columnVisibility.nonStd" label="非标" align="center" prop="nonStd" />

      <el-table-column
        v-if="columnVisibility.isMatche"
        label="匹配"
        align="center"
        prop="isMatche"
        width="180"
      />

      <el-table-column
        v-if="columnVisibility.flightCount"
        label="航班量统计"
        align="center"
        prop="flightCount"
      />

      <el-table-column
        v-if="columnVisibility.createTime"
        label="创建时间"
        align="center"
        prop="createTime"
        :formatter="dateFormatter"
        width="180px"
      />
    </el-table>
    <!-- 分页 -->
    <Pagination
      :total="total"
      v-model:page="queryParams.pageNo"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />
  </ContentWrap>

  <!-- 列设置弹窗 -->
  <el-dialog
    title="表格列设置"
    v-model="columnSettingVisible"
    width="800px"
    :close-on-click-modal="false"
  >
    <el-checkbox-group v-model="selectedColumns" class="column-setting-group">
      <el-checkbox
        v-for="column in tableColumns"
        :key="column.prop"
        :label="column.prop"
        style="width: 20%"
      >
        {{ column.label }}
      </el-checkbox>
    </el-checkbox-group>
    <template #footer>
      <el-button @click="columnSettingVisible = false">取消</el-button>
      <el-button type="primary" @click="saveColumnSettings">确定</el-button>
    </template>
  </el-dialog>

  <!-- 表单弹窗：添加/修改 -->
  <QuarterPlanForm ref="formRef" @success="getList" />
  <!-- 用户导入对话框 -->
  <QuarterPlanImportForm ref="importFormRef" @success="getList" />
</template>

<script setup lang="ts">
import { dateFormatter } from '@/utils/formatTime'
import download from '@/utils/download'
import { QuarterPlanApi, QuarterPlanVO } from '@/api/distm/quarterplan'
import QuarterPlanForm from './QuarterPlanForm.vue'
import QuarterPlanImportForm from './QuarterPlanImportForm.vue'

/** 配送管理-季度计划 列表 */
defineOptions({ name: 'QuarterPlan' })

const message = useMessage() // 消息弹窗
const { t } = useI18n() // 国际化

const loading = ref(true) // 列表的加载中
const list = ref<QuarterPlanVO[]>([]) // 列表的数据
const total = ref(0) // 列表的总页数
const queryParams = reactive({
  pageNo: 1,
  pageSize: 10,
  mealUnit: undefined,
  flightNo: undefined,
  aircraftType: undefined,
  depIata: undefined,
  arrLoc: undefined,
  arrTime: [],
  crewMeal: undefined
})
const queryFormRef = ref() // 搜索的表单
const exportLoading = ref(false) // 导出的加载中

/** 查询列表 */
const getList = async () => {
  loading.value = true
  try {
    const data = await QuarterPlanApi.getQuarterPlanPage(queryParams)
    list.value = data.list
    total.value = data.total
  } finally {
    loading.value = false
  }
}

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.pageNo = 1
  getList()
}

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value.resetFields()
  handleQuery()
}

/** 添加/修改操作 */
const formRef = ref()
const openForm = (type: string, id?: number) => {
  formRef.value.open(type, id)
}

/** 删除按钮操作 */
const handleDelete = async (id: number) => {
  try {
    // 删除的二次确认
    await message.delConfirm()
    // 发起删除
    await QuarterPlanApi.deleteQuarterPlan(id)
    message.success(t('common.delSuccess'))
    // 刷新列表
    await getList()
  } catch {}
}

/** 导出按钮操作 */
const handleExport = async () => {
  try {
    // 导出的二次确认
    await message.exportConfirm()
    // 发起导出
    exportLoading.value = true
    const data = await QuarterPlanApi.exportQuarterPlan(queryParams)
    download.excel(data, '配送管理-季度计划.xls')
  } catch {
  } finally {
    exportLoading.value = false
  }
}

/** 用户导入 */
const importFormRef = ref()
const handleImport = () => {
  importFormRef.value.open()
}

/** 表格列配置相关逻辑 **/
// 定义所有表格列（移除序号列，使其不参与配置）
const tableColumns = [
  { prop: 'mealUnit', label: '配餐单位' },
  { prop: 'flightNo', label: '航班号' },
  { prop: 'aircraftType', label: '机型' },
  { prop: 'schPat', label: '班期' },
  { prop: 'depLoc', label: '起飞地点' },
  { prop: 'depIata', label: '三字代码' },
  { prop: 'depTime', label: '起飞时间' },
  { prop: 'arrLoc', label: '降落地点' },
  { prop: 'arrIata', label: '三字代码' },
  { prop: 'arrTime', label: '降落时间' },
  { prop: 'flyDur', label: '公布飞行时长' },
  { prop: 'avgActualDur', label: '平均飞行时长' },
  { prop: 'flightType', label: '航班性质' },
  { prop: 'bussClassMealQty', label: '商务舱' },
  { prop: 'premEcoClassMeal', label: '高级经济舱' },
  { prop: 'ecoClassMeal', label: '经济舱' },
  { prop: 'crewMeal', label: '机组' },
  { prop: 'weeklyMealQty', label: '周配餐量' },
  { prop: 'airlineComp', label: '所属公司' },
  { prop: 'airlineIata', label: '所属公司三字代码' },
  { prop: 'airlineType', label: '航线类别' },
  { prop: 'effectiveDate', label: '执行日期' },
  { prop: 'remarks', label: '备注' },
  { prop: 'isWaterPkg', label: '小水放袋/盒' },
  { prop: 'isConnFlight', label: '联程航班' },
  { prop: 'cateringSite', label: '航食站点' },
  { prop: 'nonStd', label: '非标' },
  { prop: 'isMatche', label: '匹配' },
  { prop: 'flightCount', label: '航班量统计' },
  { prop: 'createTime', label: '创建时间' }
]

// 控制列显示的变量
const columnVisibility = ref({})
// 选中的列（用于多选框组）
const selectedColumns = ref<string[]>([])
// 列设置弹窗显示状态
const columnSettingVisible = ref(false)

// 初始化列显示状态（默认全部显示）
const initColumnVisibility = () => {
  const visibility = {}
  const selected = []

  tableColumns.forEach((column) => {
    visibility[column.prop] = true
    selected.push(column.prop)
  })

  columnVisibility.value = visibility
  selectedColumns.value = selected
}

// 打开列设置弹窗
const openColumnSetting = () => {
  columnSettingVisible.value = true
}

// 保存列设置
const saveColumnSettings = () => {
  const newVisibility = {}

  // 先将所有列设置为隐藏
  tableColumns.forEach((column) => {
    newVisibility[column.prop] = false
  })

  // 再将选中的列设置为显示
  selectedColumns.value.forEach((prop) => {
    newVisibility[prop] = true
  })

  columnVisibility.value = newVisibility
  columnSettingVisible.value = false
}

/** 初始化 **/
onMounted(() => {
  initColumnVisibility()
  getList()
})
</script>

<style scoped>
/* 列设置弹窗样式 */
.column-setting-group {
  max-height: 300px;
  overflow-y: auto;
  padding-right: 10px;
}

:deep(.column-setting-group .el-checkbox) {
  display: block;
  margin-bottom: 10px;
}
</style>
    